package git.soulbgm.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.regex.Pattern;

/**
 * IP相关工具类
 *
 * @author SoulBGM
 * @date 2021/8/22 22:19
 */
public class IpUtil {

    /**
     * 获取本地主机IP
     *
     * @param prefixHost IP前缀
     * @return IP地址
     */
    public static String getLocalHost(String prefixHost) {
        String localHostIp = null;
        Enumeration<NetworkInterface> netInterfaces;
        try {
            netInterfaces = NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                NetworkInterface ni = netInterfaces.nextElement();
                String displayName = ni.getDisplayName();
                String name = ni.getName();
                // 判断网络接口的名称不能为 lo获得docker 我们要找的应该是 eth0
                if (!name.contains("docker") && !name.contains("lo") && !displayName.contains("VMware")) {
                    Enumeration<InetAddress> ips = ni.getInetAddresses();
                    while (ips.hasMoreElements()) {
                        InetAddress inetAddress = ips.nextElement();
                        // 不是回环地址 127.0.0.1
                        if (!inetAddress.isLoopbackAddress()) {
                            String ip = inetAddress.getHostAddress();
                            if (isIp(ip)) {
                                if (prefixHost != null && ip.startsWith(prefixHost)) {
                                    localHostIp = ip;
                                    break;
                                } else if (prefixHost == null) {
                                    localHostIp = ip;
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.err.println("get ip error." + e);
        }
        if (localHostIp == null) {
            throw new RuntimeException("get ip error. local_ip = null.");
        }
        return localHostIp;
    }

    /**
     * 获取本地主机IP
     *
     * @return IP地址
     */
    public static String getLocalHost() {
        return getLocalHost(null);
    }

    /**
     * IP的正则表达式
     */
    private static final Pattern IP_PATTERN = Pattern.compile("^((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.){3}(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])$");

    /**
     * 判断是否是IP地址的字符串
     *
     * @param ipAddress IP地址
     * @return boolean
     */
    private static boolean isIp(String ipAddress) {
        return IP_PATTERN.matcher(ipAddress).matches();
    }

}
